package com.dyh.quickdemozwei.forCollector;


import com.google.common.collect.Lists;

import java.util.*;
import java.util.function.Function;

public class RoundCollect {

    interface Collector<T>{
        void collect(Object obj,T t);
    }

    public static <E> void pass(List<E> list,
                                Object... args){
        for (E e : list) {

            for (int i=0;i<args.length-1;i+=2){
                Object container = args[i];
                Collector collector = (Collector)args[i+1];
                collector.collect(container,e);
            }

        }
    }

    public static class SetCollector<E,T> implements Collector<T>{


        Function<T,E> function;


        public static <E,T>  SetCollector<E,T> from(Function<T,E> function){
            SetCollector<E,T>  collector = new SetCollector<>();
            collector.function = function;
            return collector;
        }


        public void collect(Set<E> container,T t) {
            container.add(function.apply(t));
        }

        @Override
        public void collect(Object obj, T t) {
            collect((Set)obj,t);
        }
    }

    public static class ListCollector<E,T> implements Collector<T>{


        Function<T,E> function;


        public static <E,T>  ListCollector<E,T> from(Function<T,E> function){
            ListCollector<E,T>  collector = new ListCollector<>();
            collector.function = function;
            return collector;
        }


        public void collect(List<E> container,T t) {
            container.add(function.apply(t));
        }

        @Override
        public void collect(Object obj, T t) {
            collect((List)obj,t);
        }
    }

    public static class MapCollector<K,V,T> implements Collector<T>{

        Function<T,K> keyFunction;
        Function<T,V> valueFunction;

        public static <K,V,T>   MapCollector<K,V,T> from(  Function<T,K> keyFunction,Function<T,V> valueFunction){
            MapCollector<K,V,T>   collector = new MapCollector<>();
            collector.keyFunction = keyFunction;
            collector.valueFunction = valueFunction;
            return collector;
        }

        public void collect(Map<K,V> container,T t) {
            container.put(keyFunction.apply(t),valueFunction.apply(t));
        }

        @Override
        public void collect(Object obj, T t) {
            collect((Map)obj,t);
        }
    }


    public static void main(String[] args) {
        List<Integer> list = Lists.newArrayList(1,2,3);

        SetCollector<Integer,Integer> c1 = SetCollector.from(e->e*2);
        MapCollector<String,Integer,Integer> c2 = MapCollector.from(String::valueOf,e->e*2);

        Set<Integer> set1 = new HashSet<>();
        Map<String,Integer> map1 = new HashMap<>();
        pass(list,
                set1,c1,
                map1,c2);

        System.out.println();
    }
}
